/*
 * $RCSfile: ConnectionAction.java,v $
 * $Revision: 1.1 $
 * $Date: 2013-03-26 $
 *
 * Copyright (C) 2008 Skin, Inc. All rights reserved.
 *
 * This software is the proprietary information of Skin, Inc.
 * Use is subject to license terms.
 */
package com.skin.generate.action;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.skin.j2ee.action.BaseAction;
import com.skin.j2ee.annotation.UrlPattern;
import com.skin.j2ee.util.Response;
import com.skin.util.HtmlUtil;
import com.skin.webcat.database.Database;
import com.skin.webcat.database.Table;
import com.skin.webcat.database.TableType;
import com.skin.webcat.database.dialect.Dialect;
import com.skin.webcat.util.Jdbc;
import com.skin.webcat.util.Webcat;

/**
 * <p>Title: ConnectionAction</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2006</p>
 * @author xuesong.net
 * @version 1.0
 */
public class ConnectionAction extends BaseAction {
    private static final Logger logger = LoggerFactory.getLogger(TableAction.class);
    
    /**
     * @throws IOException 
     */
    @UrlPattern("/generate/database/getDatabaseXml.html")
    public void getDatabaseXml() throws IOException {
        String contextPath = this.getContextPath();
        StringBuilder buffer = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
        buffer.append("<tree>");
        List<String> connections = Webcat.getConnectionList();

        for(String name : connections) {
            String connectionName = this.encode(name);
            buffer.append("<treeNode");
            buffer.append(" title=\"");
            buffer.append(HtmlUtil.encode(name));
            buffer.append("\" href=\"javascript:void(0)");
            buffer.append("\">");

            buffer.append("<treeNode");
            buffer.append(" icon=\"table.gif\"");
            buffer.append(" title=\"Tables\"");
            buffer.append(" href=\"");
            buffer.append(contextPath);
            buffer.append("/generate/table/list.html?connectionName=");
            buffer.append(connectionName);
            buffer.append("&amp;type=TABLE\"");
            buffer.append(" nodeXmlSrc=\"");
            buffer.append(contextPath);
            buffer.append("/generate/database/getTableXml.html?connectionName=");
            buffer.append(connectionName);
            buffer.append("&amp;type=TABLE\"");
            buffer.append("/>");

            buffer.append("<treeNode");
            buffer.append(" icon=\"view.gif\"");
            buffer.append(" title=\"Views\"");
            buffer.append(" href=\"");
            buffer.append(contextPath);
            buffer.append("/generate/table/list.html?connectionName=");
            buffer.append(connectionName);
            buffer.append("&amp;type=VIEW\"");
            buffer.append(" nodeXmlSrc=\"");
            buffer.append(contextPath);
            buffer.append("/generate/database/getTableXml.html?connectionName=");
            buffer.append(connectionName);
            buffer.append("&amp;type=VIEW\"");
            buffer.append("/>");
            buffer.append("</treeNode>");
        }

        File file = Webcat.getWork(this.servletContext);

        if(file.exists() && file.isDirectory()) {
            buffer.append("<treeNode");
            buffer.append(" icon=\"dir.gif\"");
            buffer.append(" title=\"sqls\"");
            buffer.append(" href=\"");
            buffer.append(contextPath);
            buffer.append("/webcat/sql/fileList.html?path=/\"");
            buffer.append(" nodeXmlSrc=\"");
            buffer.append(contextPath);
            buffer.append("/generate/database/getFolderXml.html?path=%2f\"");
            buffer.append("/>\r\n");
        }
        buffer.append("</tree>");
        this.response.setHeader("Cache-Control", "no-cache");
        this.response.setHeader("Pragma", "no-cache");
        this.response.setHeader("Expires", "0");
        Response.write(this.request, this.response, "text/xml; charset=UTF-8", buffer.toString());
    }

    /**
     * @throws ServletException
     * @throws IOException
     */
    @UrlPattern("/generate/database/getFolderXml.html")
    public void getFolderXml() throws ServletException, IOException {
        String path = this.getTrimString("path");
        String contextPath = this.getContextPath();
        StringBuilder buffer = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        buffer.append("<tree>\r\n");

        try {
            File work = Webcat.getWork(this.servletContext);
            File file = Webcat.getFile(this.servletContext, path);

            if(file != null && file.isDirectory()) {
                File[] files = file.listFiles();
                int startIndex = work.getAbsolutePath().length();

                if(files != null && files.length > 0) {
                    for(File f : files) {
                        if(f.isDirectory()) {
                            String fileName = HtmlUtil.encode(f.getName());
                            String filePath = this.encode(f.getAbsolutePath().substring(startIndex));
                            buffer.append("<treeNode");
                            buffer.append(" icon=\"dir.gif\"");
                            buffer.append(" title=\"");
                            buffer.append(fileName);
                            buffer.append("\"");
                            buffer.append(" href=\"");
                            buffer.append(contextPath);
                            buffer.append("/webcat/sql/fileList.html?path=");
                            buffer.append(filePath);
                            buffer.append("\"");
                            buffer.append(" nodeXmlSrc=\"");
                            buffer.append(contextPath);
                            buffer.append("/webcat/getFolderXml.html?path=");
                            buffer.append(filePath);
                            buffer.append("\"/>\r\n");
                        }
                    }

                    for(File f : files) {
                        if(f.isFile() && f.getName().endsWith(".sql")) {
                            String fileName = HtmlUtil.encode(f.getName());
                            String filePath = this.encode(f.getAbsolutePath().substring(startIndex));
                            buffer.append("<treeNode");
                            buffer.append(" icon=\"script.gif\"");
                            buffer.append(" title=\"");
                            buffer.append(fileName);
                            buffer.append("\"");
                            buffer.append(" href=\"");
                            buffer.append(contextPath);
                            buffer.append("/webcat/sql/list.html?path=");
                            buffer.append(filePath);
                            buffer.append("&amp;type=TABLE\"");
                            buffer.append(" nodeXmlSrc=\"");
                            buffer.append(contextPath);
                            buffer.append("/webcat/sql/getTableXml.html?path=");
                            buffer.append(filePath);
                            buffer.append("&amp;type=TABLE\"");
                            buffer.append("/>\r\n");
                        }
                    }
                }
            }
        }
        catch(Exception e) {
            logger.error(e.getMessage(), e);
        }
        buffer.append("</tree>");
        Response.write(this.request, this.response, "text/xml; charset=utf-8", buffer.toString());
    }

    /**
     * @throws IOException 
     */
    @UrlPattern("/generate/database/getTableXml.html")
    public void getTableXml() throws IOException {
        String contextPath = this.getContextPath();
        String connectionName = this.request.getParameter("connectionName");
        String[] types = TableType.getTypes(this.request.getParameterValues("type"));
        StringBuilder buffer = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        buffer.append("<tree>");
        Connection connection = null;

        try {
            connection = Webcat.getConnection(connectionName);
            Dialect dialect = Database.getDialect(connection);
            List<Table> tableList = dialect.getTableList(null, null, "%", types, false);

            if(tableList != null && tableList.size() > 0) {
                for(Table table : tableList) {
                    buffer.append("<treeNode");
                    buffer.append(" title=\"");
                    buffer.append(HtmlUtil.encode(table.getTableName()));
                    buffer.append("\"");
                    buffer.append(" href=\"");
                    buffer.append(contextPath);
                    buffer.append("/generate/table/edit.html?connectionName=");
                    buffer.append(this.encode(connectionName));
                    buffer.append("&amp;tableName=");
                    buffer.append(this.encode(table.getTableName()));
                    buffer.append("\"/>");
                }
            }
        }
        catch(SQLException e) {
            logger.error(e.getMessage(), e);
        }
        finally {
            Jdbc.close(connection);
        }

        buffer.append("</tree>");
        this.response.setHeader("Cache-Control", "no-cache");
        this.response.setHeader("Pragma", "no-cache");
        this.response.setHeader("Expires", "0");
        Response.write(this.request, this.response, "text/xml; charset=UTF-8", buffer.toString());
    }

    /**
     * @param text
     * @return String
     */
    private String encode(String text) {
        try {
            return HtmlUtil.encode(URLEncoder.encode(text, "utf-8"), "utf-8");
        }
        catch(UnsupportedEncodingException e) {
        }
        return "";
    }
}
